<?php
namespace app\common\controller;
use think\Controller;
use think\Db;
use think\cache\driver\Redis;
use app\common\logic\FfcPayment;
use app\common\logic\JspkPayment;

class JspkAll extends Controller {
    protected $czid;
    protected $time;
    protected $redis;
    
    
    public function _initialize() {
        parent::_initialize();
        set_time_limit(0);
        $this->czid = '63';
        $this->time = time();
        $this->redis = new Redis();
    }
    /************************************开奖   sTART ****************************************************/ 

	 /**
     * 开奖结果计算 20188/18
     */
    public function kj_index() {
		$big =1;   //大
		$small = 2; //小
		$single =3;    //单
		$double =4;    //双
		$ks = array();
		$he=0;
		$kjj = array();
		$dig_small ='';
		$jg = array();
		$zong = array();
		$weizhi = array('gj'=>'','yj'=>'','jj'=>'',4=>'',5=>'',6=>'',7=>'',8=>'',9=>'',10=>'');
		$arr = array('01','02','03','04','05','06','07','08','09','10');
		$tj = array();
		//获取最新应开奖期号
        $info = Db::name('kjjg_list')->where(['czid'=>$this->czid,'kjjg'=>'0'])->field('qihao,jztime')->where('jztime','<',$this->time)->order('id','DESC')->find();
  
	    $qihao =$info['qihao'];  
		
		$aa = self:: getCurrentResult($qihao);
		foreach ($aa as $key=>$it){
		    $single = $it['single'];
			$double = $it['double'];
			$big = $it['big'];
			$small = $it['small'];
			$zong[$key]=intval($it['single'])+intval($it['double'])+intval($it['big'])+intval($it['small']);
			if($single+$double+$big+$small>0){
				($big>$small) ? $dig_small=2:$dig_small=1;
				($single>$double) ? $sin_dou=4: $sin_dou=3;
				$kjj[$key] = $this->res($dig_small,$sin_dou,$key);
				
			}else{
				if($key==141){
			        shuffle($arr);
			        $kjj[$key] = implode('', $arr);
				}else{
					$i = rand(0,9);
					$kjj[$key] = $arr[$i];
				}
			}
			if($key!=141){
				$he += $zong[$key];
			}
		}
		 if(!empty($kjj)){
		 	$kjj = array_unique($kjj);
		 	foreach ($kjj as $k=>$v){
		 		if($k!=141){
		 			$ks[]=$k;
		 		}
		 	}
		 	$arr = array_values(array_diff($arr, $kjj));
			if($zong[141]>$he){
				$kjj = $kjj[141];
			}else{
				foreach ($weizhi as $t=>&$v){
					 if(in_array($t, $ks)!==false){
					 	$v=$kjj[$t];
					 }else{
					 	if(!empty($arr)){
					 		$v = $arr[0];
						 	foreach ($arr as $key=>&$value){
						 		if($value==$v){unset($arr[$key]);}
						 	}
						 	shuffle($arr);
					 	}
					 }
				}
				$kjj = implode('', $weizhi);
				
			}
		}else{
			shuffle($arr);
			$kjj = implode('', $arr);
		} 
		
		return $kjj;
	}
	
	//统计大小单双
	static private function getCurrentResult($qihao,$czid=63){
		$filter = Db::name('caipiao_open')->where(['czid'=>$czid,'filter'=>1])->column('wfid');
		$array_filter = array();
		if(in_array('135', $filter)!==false && in_array('138', $filter)!==false){
			$list = Db::name("touzhu_list_no")->field("tzhm,tzje")->where(['czid'=>$czid,'qihao'=>$qihao])->where('wfid','IN','135,138')->select();
			$ret = ['single'=>0,'double'=>0,'big'=>0,'small'=>0];
			foreach($list as $v){
				if( strpos('单', $v['tzhm'])!==false) $ret['single']+=$v['tzje'];
				if( strpos('双', $v['tzhm'])!==false) $ret['double']+=$v['tzje'];
				if( strpos('大', $v['tzhm'])!==false) $ret['big']+=$v['tzje'];
				if( strpos('小', $v['tzhm'])!==false) $ret['small']+=$v['tzje'];
			}
			$array_filter['gj'] = $ret;
		}
		if(in_array('136', $filter)!==false && in_array('139', $filter)!==false){
			$list = Db::name("touzhu_list_no")->field("tzhm,tzje")->where(['czid'=>$czid,'qihao'=>$qihao])->where('wfid','IN','136,139')->select();
			$ret = ['single'=>0,'double'=>0,'big'=>0,'small'=>0];
			foreach($list as $v){
				if( strpos('单', $v['tzhm'])!==false) $ret['single']+=$v['tzje'];
				if( strpos('双', $v['tzhm'])!==false) $ret['double']+=$v['tzje'];
				if( strpos('大', $v['tzhm'])!==false) $ret['big']+=$v['tzje'];
				if( strpos('小', $v['tzhm'])!==false) $ret['small']+=$v['tzje'];
			}
			$array_filter['yj'] = $ret;
		}
		if(in_array('137', $filter)!==false && in_array('140', $filter)!==false){
			$list = Db::name("touzhu_list_no")->field("tzhm,tzje")->where(['czid'=>$czid,'qihao'=>$qihao])->where('wfid','IN','137,140')->select();
			$ret = ['single'=>0,'double'=>0,'big'=>0,'small'=>0];
			foreach($list as $v){
				if( strpos('单', $v['tzhm'])!==false) $ret['single']+=$v['tzje'];
				if( strpos('双', $v['tzhm'])!==false) $ret['double']+=$v['tzje'];
				if( strpos('大', $v['tzhm'])!==false) $ret['big']+=$v['tzje'];
				if( strpos('小', $v['tzhm'])!==false) $ret['small']+=$v['tzje'];
			}
			$array_filter['jj'] = $ret;
		}
		if(in_array('141', $filter)!==false){
	        $list = Db::name("touzhu_list_no")->field("tzhm,tzje")->where(['czid'=>$czid,'qihao'=>$qihao])->where('wfid',141)->select();
			$ret = ['single'=>0,'double'=>0,'big'=>0,'small'=>0];
			foreach($list as $v){
	            if( strpos('单', $v['tzhm'])!==false) $ret['single']+=$v['tzje'];
	            if( strpos('双', $v['tzhm'])!==false) $ret['double']+=$v['tzje'];
	            if( strpos('大', $v['tzhm'])!==false) $ret['big']+=$v['tzje'];
	            if( strpos('小', $v['tzhm'])!==false) $ret['small']+=$v['tzje'];
	        }
	        $array_filter['141'] = $ret;
		}
		
        return $array_filter;
    }
	//大小单双
	public function res($size,$dans,$filter){
		 //大（12~19）小（3~11）
        //小单
			if($size==2 && $dans==3){
				if($filter==141){		        
					$sum=$this->rand_sum(3,10);
					if($sum%2==0){$sum=$sum+1; }
				}else{
					$xd = array('01','03','05');
					shuffle($xd);
					$sum = $xd[0];
				}		
			}
			//小双
			if($size==2 && $dans==4){
				if($filter==141){
					$sum=$this->rand_sum(3,9);
				 	if($sum%2==1){$sum=$sum+1; }
				 }else{
				 	$xd = array('02','04');
				 	shuffle($xd);
				 	$sum = $xd[0];
				 }
			}
			//大单
			if($size==1 && $dans==3){
				if($filter==141){
			   		$sum=$this->rand_sum(11,18);
				 	if($sum%2==0){$sum=$sum+1; }
			 	}else{
			 		$xd = array('07','09');
			 		shuffle($xd);
			 		$sum = $xd[0];
			 	}
			}
		
		    //大双
			if($size==1 && $dans==4){	
				if($filter==141){
			   		$sum=$this->rand_sum(12,17);
				    if($sum%2==1){$sum=$sum+1; }
			    }else{
			    	$xd = array('06','08','10');
			    	shuffle($xd);
			    	$sum = $xd[0];
			    }
			}
			$kj = $this->arr_kjjg($sum,$filter);
		
	    return	$kj;
    }
    //开奖号码
    public  function arr_kjjg($sum,$filter){
	    $arr = array('01','02','03','04','05','06','07','08','09','10');
	    if($filter==141){
			shuffle($arr);
		    $arr_code ='';
			$arr_kj1 = $this->rand_num($sum-1);
			$arr_kj2 = $sum-$arr_kj1; 
				   
		   if($arr_kj2>11){	   
	 		    $arr_kj1=$this->rand_sum($sum/2,$sum);			
			 	$arr_kj2 = $sum-$arr_kj1;
		   }
	  
			$arr_kj[0] =$this->sprintf_num($arr_kj1);
			$arr_kj[1] =$this->sprintf_num($arr_kj2);
	        $result=array_diff($arr,$arr_kj);
	        $kj=$arr_kj[0].$arr_kj[1];
	
		   foreach($result as $k=>$v) {
				$arr_code .= $v;
		   }
		   $jg = $kj.$arr_code;
	    }else{
	    	$i = rand(0,9);
	    	$jg = $arr[$i];
	    }

		return $jg;
	}
	
    //补0
	public function sprintf_num($num){
		  $num=sprintf("%02d",$num);
	 return   $num;
	}
	
    //取随机数
	public function rand_num($max){
		if($max<1){	$max=1; }	
		if($max>10){	$max=10;	}	
		$num= mt_rand(1,$max);
	 return   $num;
	}
	
	//取大小单双和
	public  function rand_sum($min,$max){
		$sum= mt_rand($min,$max);
	 return   $sum;
	}





/************************************开奖   END ****************************************************/ 

    /**
     * 获取开奖数据并执行后续操作
     */
    public function index() {
				
		//查看过滤是否开启
	    $info = Db::name('caipai_list')->where(['id'=>$this->czid])->field('filter')->find();
		if(0==$info['filter']){
			$arr = array('01','02','03','04','05','06','07','08','09','10');
		    shuffle($arr);
		    $kjj = implode('', $arr);
		}else{
			$kjj = $this->kj_index();
		}
		echo $kjj;
		

		
		
		
	   echo "---------- 开始处理当期数据 ----------<br/><br/>";
        //获取最新应开奖期号
        $info = Db::name('kjjg_list')->where(['czid'=>$this->czid,'kjjg'=>'0'])->field('qihao,jztime')->where('jztime','<',$this->time)->order('id','DESC')->find();
        $que = Db::name('caipiao')->where(['czid'=>$this->czid,'qihao'=>$info['qihao']])->find();
        if($que){
        	$kjj = explode(',', $que['kjjg']);
        	$kjj = implode('', $kjj);
        }
        $timestamp = strtotime(date('Y-m-d H:i',$this->time).':00');
        $in = Db::name('time')->where(['czid'=>$this->czid,'jztime'=>date('H:i:s',$timestamp)])->order('id','DESC')->field('qihao')->find();
        if(strlen($in['qihao'])==1){$in['qihao'] = '000'.$in['qihao'];}
        if(strlen($in['qihao'])==2){$in['qihao'] = '00'.$in['qihao'];}
        if(strlen($in['qihao'])==3){$in['qihao'] = '0'.$in['qihao'];}
        //无数据情况补足
        if(!$info) {
        	if($in['qihao']==1440 && $in['jztime']='00:00:00') {
        		$info['qihao'] = date('Y-m-d',strtotime('-1 day')).$in['qihao'];
        	}else{
        		$info['qihao'] = date('Ymd').$in['qihao'];
        	}
            $info['jztime'] = $timestamp;
        }
		
        //---------------------最后删除-----------------------------//

        //---------------------最后删除----------------------------//
        $result = array(
                'qihao' => $info['qihao'],
                'czid' => $this->czid,
                'opencode' => $kjj,
                'pentime' => date('Y-m-d H:i:s',$this->time),
                'opentimestamp' => $this->time,
        );
        
        $result_json = json_encode($result);
        $this->insertDataRedis($result_json);
        
        //开奖结果入库
        $this->kjjgSave($this->czid,$info['qihao'],$info['jztime'],$kjj);
        //将最新开奖数据存入Redis
        $this->redis->set("result_{$this->czid}","{$info['qihao']},{$info['jztime']},{$kjj}");
        
        echo "<br/>---------- 处理当期数据完成 ----------<br/>";
        
        //生成新期数据
        $this->processingNew($info['qihao']);
        usleep(10000);
        //中奖结算
        $this->payment();
    }
    
    

    /**
     * 执行开奖数据入库操作
     */
    private function kjjgSave($czid,$qihao,$jztime,$kjjg_string) {
        // 查询是否存在本期
        $exist = Db::name('kjjg_list')->where(['qihao'=>$qihao,'czid'=>$czid])->find();
        
        if($exist) {
            if(!$exist['iftz']) {
                Db::name('kjjg_list')->where('id',$exist['id'])->data(['kjjg'=>$kjjg_string,'iftz'=>1])->update();
                echo "{$czid} 号彩第 {$qihao} 期数据更新成功<br/>";
            }
            } else {
            Db::name('kjjg_list')->data(['czid'=>$czid,'qihao'=>$qihao,'jztime'=>$jztime,'kjjg'=>$kjjg_string,'iftz'=>1])->insert();
            echo "{$czid} 号彩第 {$qihao} 期数据写入成功<br/>";
            }
    }
    
    /**
     * 生成新期数据
     */
    private function processingNew($last_qihao) {
        echo "<br/>---------- 开始生成下期数据 ----------<br/><br/>";
        //$data = Db::name('time')->where('czid',$this->czid)->where('jztime','>=',date('H:i:s',$this->time))->order('id','ASC')->find();
        $data = Db::name('time')
        ->alias('t')
        ->join('__CAIPAI_LIST__ cl','cl.id=t.czid')
        ->field('t.*,cl.cp_fp_time')
        ->where('t.czid',$this->czid)->where('t.jztime','>=',date('H:i:s',$this->time))->order('t.id','ASC')->find();
        if(strlen($data['qihao'])==1){$data['qihao'] = '000'.$data['qihao'];}
        if(strlen($data['qihao'])==2){$data['qihao'] = '00'.$data['qihao'];}
        if(strlen($data['qihao'])==3){$data['qihao'] = '0'.$data['qihao'];}
        //极速PK10
        
        $sz_time = strtotime(date('Y-m-d').$data['jztime']);

    	if(empty($data)){
       		$qihao = date('Ymd').'1440';
       		$sz_time = strtotime(date('Y-m-d ',strtotime('+1 day')).'00:00:00' );
       }else{
        	$qihao = date('Ymd').$data['qihao'];
       }
        $sz_time = floor($sz_time)-floor($data['cp_fp_time']);
        $this->insertNew($this->czid,$qihao,$sz_time,'');
        
        //将当期期号存入redis，生成新期后此期便作为上一期，便于后续操作
        $this->redis->set("secend_{$this->czid}","{$last_qihao}");

        //检查新期是否存在追号
        $trace_num = Db::name('touzhu_list_zh')->where(['czid'=>$this->czid,'qihao'=>['<=',$qihao]])->select();
        if($trace_num) {
            foreach($trace_num as $vt) {
                $data = array(
                	'czid' => $vt['czid'],'qihao' => $vt['qihao'],'tzhm' => $vt['tzhm'],'tzje' => $vt['tzje'],'dzje' => $vt['dzje'],
                    'tzzs' => $vt['tzzs'],'username' => $vt['username'],'tzhje' => $vt['tzhje'],'zjje'  => $vt['zjje'],
                    'ifqs' => $vt['ifqs'],'wfid' => $vt['wfid'],'dqpl' => $vt['dqpl'],'xzfd' => $vt['xzfd'],'fdje' => $vt['fdje'],
                    'kjjg' => $vt['kjjg'],'zjzs' => $vt['zjzs'],'nbzh' => $vt['nbzh'],'tz_time' => $vt['tz_time'],'method'=> $vt['method']
                );
				$data['from'] = 1==intval($vt['stop']) ? 1 : 2;
                Db::startTrans();
                try {
                    Db::name('touzhu_list_no')->data($data)->insert();
                    Db::name('touzhu_list_zh')->data($data)->where('id',$vt['id'])->delete();
                    Db::commit();
                    echo "{$vt['czid']} 号彩第 {$qihao} 期追号更新成功<br/>";
                } catch (\Exception $e) {
                    Db::rollback();
                    echo "{$vt['czid']} 号彩第 {$qihao} 期追号更新失败<br/>";
                }
                usleep(10000);
            }
        }

        echo "<br/>---------- 生成下期数据完成 ----------";
    }

    /**
     * 新期写入库
     */
    private function insertNew($czid,$qihao,$jztime,$pss) {
        $res = Db::name('kjjg_list')->where(['czid'=>$czid,'qihao'=>$qihao])->find();
        if(!$res) {
            Db::name('kjjg_list')->data(['czid'=>$czid,'qihao'=>$qihao,'jztime'=>$jztime,'kjjg'=>'0','iftz'=>0,'ps'=>$pss])->insert();
            echo "{$czid} 号彩第 {$qihao} 期新期写入成功";
            $this->insertNewRedis($czid,$qihao,$jztime);
        }
    }

    /**
     * 新期写入Redis
     */
    private function insertNewRedis($czid,$qihao,$jztime) {
        $this->redis->set("{$czid}","{$qihao},{$jztime},0");
        echo " Redis写入成功<br/>";
    }
    
    /**
     * 最新开奖数据写入Redis
     */
    private function insertDataRedis($data) {
        $this->redis->set('Jspk_kjjg',"{$data}");
        @file_put_contents('./jspk10log/newdata/'.date('Ymd',$this->time).'.txt',$data."\n",FILE_APPEND);
    }
    
    /**
     * 开奖结算
     */
    private function payment() {

        echo "<br/><br/>---------- 开始处理结算统计 ----------<br/>";
        $ctime = microtime(true);
        $cur_time = time();
        //非关联方式，循环查询
        /* $data_all = Db::name('touzhu_list_no')->alias('t')
                            ->join('__USERNAME__ u','t.username=u.username')
                            ->field('t.*,u.id as user_id,u.swzh,u.nbzh as nb')
                            ->where('t.czid','62')
                            ->limit(1000)
                            ->select(); */
        //关联方式，但因为开奖表数据量大，效率待定，具体说明参看logic->FfcPayment
        $data_all = Db::name('touzhu_list_no')->alias('t')
                            ->join('__KJJG_LIST__ k','t.czid=k.czid and t.qihao=k.qihao')
                            ->join('__USERNAME__ u','t.username=u.username')
                            ->field('t.*,k.kjjg,u.id as user_id,u.swzh,u.nbzh as nb')   //k.kjjg务必放在t.*之后
                            ->where('k.kjjg','<>','0')
                            ->where('t.czid','63')
                            ->limit(1000)
                            ->select();

        $count = count($data_all);
        foreach($data_all as $v) {
                $ffc = JspkPayment::getInstance();
                $payment_result = $ffc->dealInfo($v);
                if($payment_result !== false) {
                    $this->sendMessage($v['username'],'极速PK10','极速PK10',$v['qihao'],$payment_result);
                }
        }
        $time = microtime(true)-$ctime;
        $ymd = date('Y-m-d H:i:s',$cur_time);
        @file_put_contents('./jspk10log/payment/'.date('Ymd',$cur_time).'.txt',"{$ymd}，用时{$time}s，可处理{$count}条\n",FILE_APPEND);
        echo "<br/>{$time}，{$count}<br/>";
        echo "<br/>---------- 结算统计处理完成 ----------<br/>";
    }
    
    /**
     * 会员消息发送
     */
    private function sendMessage($username,$cp_name_old,$cp_name_new,$qihao,$zjje) {
        if(!$cp_name_new) $cp_name_new = $cp_name_old;
        $message = "您投注的:【{$cp_name_new}】，【{$qihao}】期已开奖，中奖金额:【{$zjje}】元！";
        $data = array(
                'username' => $username,
                'test' =>$message ,
                'xx_time' => $this->time,
                'ifdq' => 0
        );
        Db::name('xiaoxi')->data($data)->insert();
    }
}
